import asyncio
import random
from typing import List, Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum

from ai_service import AIService
from detective_ui import DetectiveUI

class CharacterType(Enum):
    SUSPECT = "suspect"      # 嫌疑人
    WITNESS = "witness"      # 证人
    VICTIM = "victim"        # 受害者（如果还活着）
    EXPERT = "expert"        # 专家（法医、技术人员等）

@dataclass
class Character:
    """游戏角色"""
    name: str
    age: int
    occupation: str
    personality: str
    background: str
    secret: str              # 角色隐藏的秘密
    alibi: str              # 不在场证明
    motive: str             # 动机（如果是嫌疑人）
    knowledge: List[str]     # 角色知道的信息
    character_type: CharacterType
    is_guilty: bool = False  # 是否是真凶
    stress_level: int = 0    # 压力值（影响回答）
    trust_level: int = 50    # 对侦探的信任度

@dataclass
class Evidence:
    """证据"""
    name: str
    description: str
    location: str
    significance: str
    discovered: bool = False

@dataclass
class Case:
    """案件"""
    title: str
    description: str
    victim_name: str
    crime_scene: str
    time_of_crime: str
    characters: List[Character]
    evidence: List[Evidence]
    solution: str            # 案件真相
    key_clues: List[str]     # 关键线索

class DetectiveGame:
    """侦探推理游戏引擎"""
    
    def __init__(self):
        self.ai_service = AIService()
        self.ui = DetectiveUI()
        self.current_case: Optional[Case] = None
        self.conversation_history: Dict[str, List[Dict]] = {}  # 每个角色的对话历史
        self.current_character: Optional[Character] = None
        self.max_rounds = 30  # 最大轮次
        self.current_round = 0
        self.hints_used = 0
        self.max_hints = 3
        
        # 预设案例库
        self.cases = self._load_cases()
        
    def _load_cases(self) -> List[Case]:
        """加载案例库"""
        return [
            Case(
                title="豪宅谋杀案",
                description="富商李明在自己的书房中被发现死亡，头部遭受重击。现场门窗紧锁，只有家人和几个客人在场。",
                victim_name="李明",
                crime_scene="李明豪宅书房",
                time_of_crime="昨晚10点到11点之间",
                characters=[
                    Character(
                        name="王美丽",
                        age=35,
                        occupation="妻子",
                        personality="表面温柔贤惠，实则心机深沉，善于伪装和操控他人情绪",
                        background="嫁给李明5年，表面恩爱实则同床异梦。最近发现丈夫出轨并准备离婚，但不想净身出户",
                        secret="已经暗中联系律师准备离婚诉讼，同时在转移夫妻共同财产。当晚与李明因财产分割发生激烈争吵",
                        alibi="声称10点后一直在厨房准备夜宵，但实际上10点半左右去过书房",
                        motive="既要报复出轨的丈夫，又要确保能继承大部分遗产",
                        knowledge=["李明的出轨证据", "家庭财产状况", "保险箱密码", "当晚每个人的大致位置"],
                        character_type=CharacterType.SUSPECT,
                        is_guilty=True
                    ),
                    Character(
                        name="李小华",
                        age=28,
                        occupation="儿子",
                        personality="叛逆冲动，沉迷赌博，但内心还有良知。说话直接不会掩饰",
                        background="大学毕业后无所事事，沉迷网络赌博。与父亲关系恶劣，经常因为钱发生争吵。最近欠下巨额赌债",
                        secret="欠了200万高利贷，催债的威胁要砍断他的手。当晚曾想向父亲求助但被拒绝",
                        alibi="声称晚上9点后一直在房间打游戏，但中途确实出来过几次",
                        motive="急需大笔资金还债，否则性命难保",
                        knowledge=["父亲的脾气和习惯", "家里的布局和作息", "当晚听到的争吵声", "王美丽最近的异常行为"],
                        character_type=CharacterType.SUSPECT
                    ),
                    Character(
                        name="张秘书",
                        age=26,
                        occupation="私人秘书",
                        personality="表面专业谨慎，内心情感复杂。观察力敏锐，善于察言观色",
                        background="名牌大学毕业，为李明工作3年。工作能力强深受信任，但暗中爱慕老板。知道很多家庭内部秘密",
                        secret="深深暗恋李明，嫉妒王美丽。发现李明出轨后既愤怒又看到了机会，幻想过李明离婚后和自己在一起",
                        alibi="声称晚上一直在客厅整理明天的工作文件，但期间去过厨房倒水",
                        motive="复杂的爱恨情仇，既想保护李明又嫉妒他的婚姻",
                        knowledge=["李明的工作安排和秘密", "王美丽的异常行为", "当晚每个人的行踪", "家庭内部矛盾"],
                        character_type=CharacterType.SUSPECT
                    ),
                    Character(
                        name="刘管家",
                        age=55,
                        occupation="管家",
                        personality="忠诚老实，但有强烈的道德观念。说话谨慎，但内心正义感很强",
                        background="在李家工作15年，从李小华小时候就照顾这个家。视李家为自己的家，对李明的背叛行为深感失望",
                        secret="知道李明所有的秘密包括外遇，也知道王美丽在转移财产。对李明的道德沦丧感到愤怒和失望",
                        alibi="晚上在厨房和餐厅之间忙碌，准备宵夜和收拾餐具",
                        motive="对李明背叛家庭的愤怒，认为他不配拥有这个家",
                        knowledge=["所有人的秘密和行踪", "家庭15年来的变化", "当晚的异常情况", "李明的作息习惯"],
                        character_type=CharacterType.SUSPECT
                    ),
                    Character(
                        name="陈医生",
                        age=45,
                        occupation="法医",
                        personality="专业，客观，注重细节",
                        background="有20年法医经验",
                        secret="无",
                        alibi="不在现场",
                        motive="无",
                        knowledge=["死亡时间", "死因分析", "现场痕迹"],
                        character_type=CharacterType.EXPERT
                    )
                ],
                evidence=[
                    Evidence("血迹铜像", "书房内的铜像底座有血迹", "书房", "可能的凶器"),
                    Evidence("破碎的酒杯", "地上有破碎的威士忌酒杯", "书房", "可能发生过争执"),
                    Evidence("保险箱", "书房的保险箱被打开过", "书房", "可能的作案动机"),
                    Evidence("手机通话记录", "受害者手机显示当晚有多个通话", "受害者身上", "了解受害者最后的活动"),
                    Evidence("脚印", "书房地毯上有不明脚印", "书房", "可能是凶手留下的")
                ],
                solution="王美丽是真凶。她发现丈夫出轨后，趁机在书房与丈夫争执，用铜像击打致死。然后伪造现场，声称在厨房准备夜宵。",
                key_clues=["王美丽的动机", "保险箱被打开", "时间线矛盾", "脚印匹配"]
            )
        ]
    
    async def start_game(self):
        """开始游戏"""
        self.ui.show_welcome()
        
        while True:
            choice = self.ui.show_main_menu()
            
            if choice == "1":
                await self.start_investigation()
            elif choice == "2":
                self.ui.show_rules()
            elif choice == "3":
                self.ui.show_goodbye()
                break
            else:
                self.ui.show_error("无效选择，请重新输入")
    
    async def start_investigation(self):
        """开始调查"""
        # 选择案件（目前只有一个）
        self.current_case = self.cases[0]
        
        # 重置游戏状态
        self.conversation_history = {char.name: [] for char in self.current_case.characters}
        self.current_character = None
        self.current_round = 0
        self.hints_used = 0
        
        # 显示案件信息
        self.ui.show_case_intro(self.current_case)
        
        # 主要调查循环
        while self.current_round < self.max_rounds:
            action = self.ui.show_investigation_menu(self.current_round, self.max_rounds, self.hints_used, self.max_hints)
            
            if action == "1":
                await self.talk_to_character()
            elif action == "2":
                if self.hints_used >= self.max_hints:
                    self.ui.show_error("提示次数已用完")
                else:
                    await self.get_hint()
            elif action == "3":
                result = await self.make_accusation()
                if result:  # 如果做出了指控，游戏结束
                    return
            elif action == "4":
                break
            else:
                self.ui.show_error("无效选择，请重新输入")
        
        # 轮次用完
        if self.current_round >= self.max_rounds:
            self.ui.show_rounds_exhausted()
            await self.make_accusation()
    
    async def talk_to_character(self):
        """与角色对话"""
        # 选择角色
        character = self.ui.select_character(self.current_case.characters)
        if not character:
            return
        
        self.current_character = character
        self.ui.show_character_info(character)
        
        # 连续对话循环
        while self.current_round < self.max_rounds:
            # 生成推荐问题
            suggested_questions = await self._generate_suggested_questions(character)
            question = self.ui.get_question(suggested_questions)
            if not question or question.strip() == '':
                break  # 空输入退出对话
            
            # 获取AI回答
            response = await self._get_character_response(character, question)
            
            # 记录对话
            conversation_record = {
                "question": question,
                "response": response
            }
            
            self.conversation_history[character.name].append(conversation_record)
            
            # 显示回答
            self.ui.show_conversation(character, question, response)
            
            # 消耗一轮
            self.current_round += 1
            
            # 显示剩余轮次
            self.ui.show_remaining_rounds(self.current_round, self.max_rounds)
            
            # 如果轮次用完，退出对话
            if self.current_round >= self.max_rounds:
                break
    
    async def _get_character_response(self, character: Character, question: str) -> str:
        """获取角色的AI回应"""
        # 构建角色的上下文信息
        context = self._build_character_context(character)
        
        # 构建对话历史
        conversation_context = ""
        if character.name in self.conversation_history:
            recent_conversations = self.conversation_history[character.name][-3:]  # 最近3轮对话
            for conv in recent_conversations:
                conversation_context += f"侦探问：{conv['question']}\n我答：{conv['response']}\n\n"
        
        # 获取在场人员列表
        present_people = [char.name for char in self.current_case.characters if char.name != character.name]
        present_people_str = "、".join(present_people)
        
        prompt = f"""你正在扮演案件中的角色{character.name}，需要根据角色设定自然地回答侦探的问题。

【角色设定】
我是{character.name}，{character.age}岁，{character.occupation}。
性格：{character.personality}
背景：{character.background}
我的秘密：{character.secret}
我的不在场证明：{character.alibi}
{"我的动机：" + character.motive if character.character_type == CharacterType.SUSPECT else ""}

【案件情况】
{self.current_case.description}
受害者是{self.current_case.victim_name}，案发时间{self.current_case.time_of_crime}，地点在{self.current_case.crime_scene}。
这是一个密室案件，只有在场的人才可能是凶手。

【在场人员】
当晚在场的人只有：{present_people_str}和我自己。

【我知道的信息】
{chr(10).join(character.knowledge)}

【对话历史】
{conversation_context}

【重要约束】
1. 这是密室推理，凶手只能是在场的人员中的一个
2. 绝对不能提到任何不在场的人物作为嫌疑人
3. 如果要怀疑别人，只能怀疑在场人员：{present_people_str}
4. 不能编造任何场外人物或事件

【回答要求】
1. 以第一人称自然回答，符合我的性格和身份
2. {"如果我是真凶，要巧妙隐瞒但不能撒谎太明显" if character.is_guilty else "诚实回答，但只说我知道的"}
3. 回答要简洁自然，不要太长
4. 保持角色一致性
5. 严格遵守密室推理规则，不提及场外人物

侦探问：{question}
我回答："""

        try:
            response = await self.ai_service.get_simple_response(prompt)
            return response.strip()
        except Exception as e:
            return f"[{character.name}显得有些紧张，没有立即回答]"
    
    def _build_character_context(self, character: Character) -> str:
        """构建角色上下文"""
        context = f"我是{character.name}，{character.age}岁，{character.occupation}。"
        
        if character.is_guilty:
            context += "我需要小心回答，不能暴露自己的罪行。"
        
        return context
    
    async def _generate_suggested_questions(self, character: Character) -> List[str]:
        """生成推荐问题"""
        # 获取对话历史
        conversation_context = ""
        if character.name in self.conversation_history:
            recent_conversations = self.conversation_history[character.name][-2:]  # 最近2轮对话
            for conv in recent_conversations:
                conversation_context += f"侦探问：{conv['question']}\n{character.name}答：{conv['response']}\n\n"
        
        # 获取在场人员
        present_people = [char.name for char in self.current_case.characters if char.name != character.name]
        present_people_str = "、".join(present_people)
        
        prompt = f"""你是一个侦探推理游戏的助手，需要为侦探生成3个最佳的问题来询问{character.name}。

【案件背景】
{self.current_case.description}
受害者：{self.current_case.victim_name}
案发时间：{self.current_case.time_of_crime}
案发地点：{self.current_case.crime_scene}

【角色信息】
{character.name}，{character.age}岁，{character.occupation}
性格：{character.personality}

【在场人员】
{present_people_str}

【已有对话】
{conversation_context if conversation_context else "尚未开始对话"}

【生成要求】
1. 生成3个不同角度的问题，帮助侦探获取关键信息
2. 问题要符合侦探推理的逻辑，不能太直接指控
3. 可以询问：不在场证明、当晚见闻、对其他人的看法、动机相关等
4. 问题要简洁明了，一句话表达
5. 不要重复已经问过的问题

请直接输出3个问题，每行一个，不要编号："""

        try:
            response = await self.ai_service.get_simple_response(prompt)
            questions = [q.strip() for q in response.strip().split('\n') if q.strip()]
            # 确保有3个问题
            while len(questions) < 3:
                questions.append(f"你能告诉我更多关于当晚的情况吗？")
            return questions[:3]
        except Exception as e:
            # 备用问题
            backup_questions = [
                "你当晚在做什么？",
                "你对其他人有什么看法？",
                "你注意到什么异常情况吗？"
            ]
            return backup_questions
    
    async def get_hint(self):
        """获取智能提示"""
        if self.hints_used >= self.max_hints:
            self.ui.show_error("提示次数已用完")
            return
        
        # 分析当前调查进度，生成智能提示
        hint = await self._generate_intelligent_hint()
        
        # 生成调查状态摘要
        investigation_summary = self._build_investigation_summary()
        
        self.hints_used += 1
        self.ui.show_hint(hint, self.hints_used, self.max_hints, investigation_summary)
    
    def _build_investigation_summary(self) -> str:
        """构建调查状态摘要"""
        summary_parts = []
        total_conversations = sum(len(convs) for convs in self.conversation_history.values())
        
        # 对话统计
        for char_name, conversations in self.conversation_history.items():
            if conversations:
                char = next(c for c in self.current_case.characters if c.name == char_name)
                summary_parts.append(f"与{char_name}({char.occupation})对话{len(conversations)}次")
        
        # 未对话的角色
        untouched_characters = [char.name for char in self.current_case.characters 
                              if char.name not in self.conversation_history or not self.conversation_history[char.name]]
        
        if untouched_characters:
            summary_parts.append(f"未对话：{', '.join(untouched_characters)}")
        
        # 调查进度
        progress_percentage = min(100, (total_conversations / (len(self.current_case.characters) * 3)) * 100)
        summary_parts.append(f"调查进度：{progress_percentage:.0f}%")
        
        return "\n".join(summary_parts) if summary_parts else "尚未开始调查"
    
    async def _generate_intelligent_hint(self) -> str:
        """根据调查进度生成智能提示"""
        # 分析对话历史
        total_conversations = sum(len(convs) for convs in self.conversation_history.values())
        talked_characters = [name for name, convs in self.conversation_history.items() if convs]
        untouched_characters = [char.name for char in self.current_case.characters 
                              if char.name not in talked_characters]
        
        # 根据不同阶段给出不同类型的提示
        if total_conversations == 0:
            # 刚开始调查
            return "建议先与所有在场人员都对话一轮，了解基本情况和每个人的不在场证明。"
        
        elif total_conversations < len(self.current_case.characters):
            # 还有人没有对话过
            untouched_names = "、".join(untouched_characters)
            return f"你还没有与{untouched_names}对话过，他们可能掌握关键信息。"
        
        elif total_conversations < len(self.current_case.characters) * 2:
            # 每个人都对话过，但还不够深入
            return await self._analyze_conversations_for_hint()
        
        else:
            # 深入调查阶段 - 进行多维度分析
            return await self._advanced_analysis_hint()
    
    async def _advanced_analysis_hint(self) -> str:
        """高级分析提示 - 多维度分析"""
        # 进行多种分析
        analyses = []
        
        # 1. 矛盾分析
        contradiction_hint = await self._analyze_contradictions_for_hint()
        if contradiction_hint and "重新检查" not in contradiction_hint:
            analyses.append(("矛盾分析", contradiction_hint))
        
        # 2. 行为模式分析
        behavior_hint = self._analyze_behavior_patterns()
        if behavior_hint:
            analyses.append(("行为分析", behavior_hint))
        
        # 3. 信息缺失分析
        missing_info_hint = self._analyze_missing_information()
        if missing_info_hint:
            analyses.append(("信息缺失", missing_info_hint))
        
        # 4. 可疑度分析
        suspicion_hint = self._analyze_suspicion_levels()
        if suspicion_hint:
            analyses.append(("可疑度分析", suspicion_hint))
        
        # 选择最有价值的提示
        if analyses:
            # 根据提示使用次数选择不同类型的分析
            analysis_type, hint = analyses[self.hints_used % len(analyses)]
            return f"【{analysis_type}】{hint}"
        
        return await self._analyze_contradictions_for_hint()
    
    def _analyze_behavior_patterns(self) -> str:
        """分析角色行为模式"""
        behavior_indicators = []
        
        for char_name, conversations in self.conversation_history.items():
            if not conversations:
                continue
                
            char = next(c for c in self.current_case.characters if c.name == char_name)
            responses = [conv['response'].lower() for conv in conversations]
            response_text = " ".join(responses)
            
            # 分析回避行为
            evasive_words = ["不记得", "忘记", "不清楚", "不知道", "可能", "大概"]
            evasive_count = sum(1 for word in evasive_words if word in response_text)
            
            # 分析情绪词汇
            nervous_words = ["紧张", "害怕", "担心", "不安"]
            nervous_count = sum(1 for word in nervous_words if word in response_text)
            
            # 分析防御性语言
            defensive_words = ["不是我", "我没有", "绝对不", "怎么可能"]
            defensive_count = sum(1 for word in defensive_words if word in response_text)
            
            if evasive_count >= 2:
                behavior_indicators.append(f"{char_name}的回答很模糊，可能在隐瞒什么")
            if nervous_count >= 1:
                behavior_indicators.append(f"{char_name}表现出紧张情绪")
            if defensive_count >= 2:
                behavior_indicators.append(f"{char_name}的回答很防御性")
        
        if behavior_indicators:
            return behavior_indicators[0]  # 返回最重要的行为指标
        
        return ""
    
    def _analyze_missing_information(self) -> str:
        """分析缺失的关键信息"""
        # 检查是否收集了关键信息类型
        all_responses = []
        for conversations in self.conversation_history.values():
            for conv in conversations:
                all_responses.append(conv['response'].lower())
        
        response_text = " ".join(all_responses)
        
        missing_info = []
        
        # 检查时间相关信息
        if "点" not in response_text and "时间" not in response_text:
            missing_info.append("具体的时间信息")
        
        # 检查位置信息
        if "房间" not in response_text and "地方" not in response_text and "哪里" not in response_text:
            missing_info.append("详细的位置信息")
        
        # 检查动机信息
        if "为什么" not in response_text and "原因" not in response_text and "动机" not in response_text:
            missing_info.append("动机相关信息")
        
        # 检查关系信息
        if "关系" not in response_text and "认识" not in response_text:
            missing_info.append("人物关系信息")
        
        if missing_info:
            return f"还缺少{missing_info[0]}，建议针对性询问"
        
        return ""
    
    def _analyze_suspicion_levels(self) -> str:
        """分析各角色的可疑程度"""
        suspicion_scores = {}
        
        for char_name, conversations in self.conversation_history.items():
            if not conversations:
                continue
                
            char = next(c for c in self.current_case.characters if c.name == char_name)
            score = 0
            
            # 基于对话内容计算可疑度
            for conv in conversations:
                response = conv['response'].lower()
                question = conv['question'].lower()
                
                # 回避问题加分
                if any(word in response for word in ["不记得", "忘记", "不清楚"]):
                    score += 2
                
                # 防御性回答加分
                if any(word in response for word in ["不是我", "我没有", "绝对不"]):
                    score += 1
                
                # 提供详细信息减分
                if len(response) > 50 and any(word in response for word in ["当时", "我看到", "我听到"]):
                    score -= 1
                
                # 主动提供线索减分
                if any(word in response for word in ["我觉得", "可能是", "我怀疑"]):
                    score -= 1
            
            suspicion_scores[char_name] = score
        
        if suspicion_scores:
            # 找出最可疑的角色
            most_suspicious = max(suspicion_scores.items(), key=lambda x: x[1])
            least_suspicious = min(suspicion_scores.items(), key=lambda x: x[1])
            
            if most_suspicious[1] > 2:
                return f"{most_suspicious[0]}的回答最可疑，建议深入追问"
            elif least_suspicious[1] < 0:
                return f"{least_suspicious[0]}很配合调查，可能不是凶手"
        
        return ""
    
    async def _analyze_conversations_for_hint(self) -> str:
        """分析对话内容生成提示"""
        # 收集所有对话内容
        all_conversations = []
        for char_name, conversations in self.conversation_history.items():
            for conv in conversations:
                all_conversations.append(f"{char_name}: {conv['question']} -> {conv['response']}")
        
        if not all_conversations:
            return "建议开始与在场人员对话，了解案发当晚的情况。"
        
        # 构建分析提示的prompt
        conversations_text = "\n".join(all_conversations[-10:])  # 最近10轮对话
        
        prompt = f"""你是一个侦探推理游戏的智能助手，需要分析玩家的调查进度并给出有针对性的提示。

【案件信息】
{self.current_case.description}
受害者：{self.current_case.victim_name}
案发时间：{self.current_case.time_of_crime}
案发地点：{self.current_case.crime_scene}

【在场人员】
{chr(10).join([f"{char.name}({char.occupation})" for char in self.current_case.characters])}

【已进行的对话】
{conversations_text}

【分析要求】
1. 分析玩家已经收集到的信息
2. 识别还缺少哪些关键信息
3. 发现对话中的矛盾点或可疑之处
4. 给出具体的调查建议

请给出一个简洁但有针对性的提示（不超过50字），帮助玩家推进调查："""

        try:
            response = await self.ai_service.get_simple_response(prompt)
            return response.strip()
        except Exception as e:
            # 备用分析
            return self._fallback_conversation_analysis()
    
    async def _analyze_contradictions_for_hint(self) -> str:
        """分析矛盾点生成提示"""
        # 收集所有对话内容
        all_conversations = []
        for char_name, conversations in self.conversation_history.items():
            for conv in conversations:
                all_conversations.append(f"{char_name}: Q:{conv['question']} A:{conv['response']}")
        
        conversations_text = "\n".join(all_conversations)
        
        prompt = f"""你是侦探推理专家，需要分析对话中的矛盾和线索。

【案件背景】
{self.current_case.description}
受害者：{self.current_case.victim_name}
案发时间：{self.current_case.time_of_crime}

【所有对话记录】
{conversations_text}

【分析任务】
1. 寻找不同人说法之间的矛盾
2. 识别可疑的回避或模糊回答
3. 发现时间线上的问题
4. 找出动机和机会的线索

请给出一个具体的提示（不超过60字），指出最值得深入调查的方向："""

        try:
            response = await self.ai_service.get_simple_response(prompt)
            return response.strip()
        except Exception as e:
            return self._fallback_contradiction_analysis()
    
    def _fallback_conversation_analysis(self) -> str:
        """备用对话分析"""
        # 简单的关键词分析
        all_responses = []
        for conversations in self.conversation_history.values():
            for conv in conversations:
                all_responses.append(conv['response'].lower())
        
        response_text = " ".join(all_responses)
        
        # 检查常见的可疑词汇
        if "不记得" in response_text or "忘记" in response_text:
            return "注意那些声称'不记得'或'忘记'的人，这可能是在隐瞒什么。"
        elif "不在" in response_text or "离开" in response_text:
            return "仔细核实每个人的不在场证明，看看时间是否对得上。"
        elif "听到" in response_text or "声音" in response_text:
            return "有人提到听到声音，这可能是确定案发时间的关键线索。"
        else:
            return "重新审视每个人的动机，谁最有理由伤害受害者？"
    
    def _fallback_contradiction_analysis(self) -> str:
        """备用矛盾分析"""
        # 统计每个角色的对话次数
        char_talk_counts = {name: len(convs) for name, convs in self.conversation_history.items()}
        
        # 找出对话最少的角色
        if char_talk_counts:
            min_talks = min(char_talk_counts.values())
            least_talked = [name for name, count in char_talk_counts.items() if count == min_talks]
            
            if least_talked and min_talks < 3:
                return f"建议深入询问{least_talked[0]}，他们的信息还不够充分。"
        
        return "重新检查每个人的时间线，看看谁的说法前后不一致。"
    
    async def make_accusation(self):
        """做出指控"""
        suspect = self.ui.select_suspect(self.current_case.characters)
        if not suspect:
            return False
        
        reasoning = self.ui.get_accusation_reasoning()
        
        # 检查指控是否正确
        if suspect.is_guilty:
            self.ui.show_success(suspect, self.current_case.solution)
        else:
            self.ui.show_failure(suspect, self.current_case.solution)
        
        # 显示完整真相
        self.ui.show_case_solution(self.current_case)
        return True

# 主函数
async def main():
    game = DetectiveGame()
    await game.start_game()

if __name__ == "__main__":
    asyncio.run(main()) 